package com.shangxia.monomer.study.thread.base;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ProjectName: monomer
 * @ClassName: Unsafe
 * @Time: 2021/9/27
 * @Author: zhouy
 * @Description:
 * @Experience:
 */

@Slf4j
public class Unsafe {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        Map list1= new ConcurrentHashMap();

//        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                synchronized (list) {
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }
        System.out.println(list.size());
    }

    private static void test01() {
        Account account = new Account(100);
        DrawingMoney drawingMoney = new DrawingMoney(account, 80);
        DrawingMoney drawingMoney2 = new DrawingMoney(account, 80);
        new Thread(drawingMoney).start();
        new Thread(drawingMoney2).start();
    }
}

@AllArgsConstructor
class DrawingMoney implements Runnable {
    private Account account;
    private Integer money;

    @Override
    public void run() {
        synchronized (account) {
            if (account.getMoney() < money) {
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "取" + money);
            account.setMoney(account.getMoney() - money);
        }
        System.out.println(account.getMoney());
    }
}

@Data
@AllArgsConstructor
class  Account {
    private Integer money;
}
